﻿namespace Example.Cryptography
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Security.Cryptography;
    using System.Text;

    [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sha", Justification = "The casing is correct.")]
    public sealed class ShaPlaintext
    {
        private byte[] _plaintext;

        public ShaPlaintext(string plaintext)
            : this(Encoding.UTF8.GetBytes(plaintext))
        {
        }

        public ShaPlaintext(byte[] plaintext)
        {
            Plaintext = plaintext;
        }

        private byte[] Plaintext
        {
            get
            {
                return _plaintext;
            }

            set
            {
                if (null == value)
                {
                    throw new ArgumentNullException("value");
                }

                _plaintext = value;
            }
        }

        public ShaCiphertext Encrypt(Salt salt)
        {
            if (null == salt)
            {
                throw new ArgumentNullException("salt");
            }

            ShaCiphertext ciphertext;

            var bytes = new byte[Plaintext.Length + salt.ToBytes().Length];
            Plaintext.CopyTo(bytes, 0);
            salt.ToBytes().CopyTo(bytes, Plaintext.Length);

            using (HashAlgorithm algorithm = new SHA256Managed())
            {
                ciphertext = new ShaCiphertext(salt, algorithm.ComputeHash(bytes));
            }

            return ciphertext;
        }

        public byte[] ToBytes()
        {
            return Plaintext;
        }

        public override string ToString()
        {
            return Convert.ToBase64String(Plaintext);
        }
    }
}